﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using KOPLibrary.TemplateManagement;
using System.Security.Cryptography;
using System.IO;

namespace KOPLibrary.Forms
{
    public partial class ProtectDocument : Form
    {

        private TemplateType templateType { get; set; }
        private string destinationFile = null;
        public ProtectDocument()
        {
            InitializeComponent();
        }

        private void ProtectDocument_Load(object sender, EventArgs e)
        {
            ctlPassword.Focus();
        }

        public static string ExecuteProtectDocument(TemplateType type)
        {
            ProtectDocument form = new ProtectDocument();
            form.templateType = type;
            return form.Execute();
        }

        private string Execute()
        {
            DialogResult result = ShowDialog();
            if (result == DialogResult.OK && !string.IsNullOrEmpty(destinationFile))
            {
                byte[] salt = Encoding.ASCII.GetBytes(ctlPassword.Text);
                Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(ctlPassword.Text, salt);


                AesManaged aes = new AesManaged();
                aes.Key = rfc.GetBytes(32);
                aes.IV = Encoding.ASCII.GetBytes("0123456789ABCDRE");

                byte[] docKey = new Rfc2898DeriveBytes(ctlPassword.Text, 
                    Encoding.ASCII.GetBytes(DateTime.Now.ToLongTimeString())).GetBytes(15);

                ICryptoTransform transform = aes.CreateEncryptor();
                using (FileStream fs = new FileStream(destinationFile, FileMode.Create))
                {
                    using (CryptoStream cr = new CryptoStream(fs, transform, CryptoStreamMode.Write))
                    {
                        cr.Write(docKey, 0, docKey.Length);
                        cr.Close();
                    }
                    fs.Close();
                }
                return Encoding.ASCII.GetString(docKey);
            }
            else return "";
        }

        private void ctlGo_Click(object sender, EventArgs e)
        {
            if (ctlPassword.Text != ctlRePassword.Text)
                Util.ShowError("Şifreler birbirleriyle uyumlu değil");
            else if (ctlPassword.Text.Length < 8)
                Util.ShowError("Şifreniz en az 8 (sekiz) karakter uzunluğunda olmalıdır.");
            else if (sfd.ShowDialog() == DialogResult.OK)
            {
                destinationFile = sfd.FileName;
                DialogResult = DialogResult.OK;
            }
        }
    }
}
